package com.nsgf.library.ui.product;

import static android.view.View.GONE;
import static android.view.View.VISIBLE;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.KeyEvent;
import android.view.inputmethod.EditorInfo;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.RecyclerView;

import com.kunminx.architecture.ui.page.DataBindingConfig;
import com.kunminx.architecture.ui.state.State;
import com.kunminx.binding_recyclerview.adapter.BaseDataBindingAdapter;
import com.kunminx.binding_recyclerview.adapter.SimpleDataBindingAdapter;
import com.nsgf.library.ui.adapter.DiffUtils;
import com.nsgf.library.utils.StringUtil;
import com.zhht.htzx.BR;
import com.zhht.htzx.R;
import com.nsgf.library.data.api.AccountService;
import com.nsgf.library.data.bean.LibraryInfo;
import com.nsgf.library.data.bean.ProductBean;
import com.nsgf.library.data.response.ResponseStatus;
import com.zhht.htzx.databinding.ActivityProductListBinding;
import com.zhht.htzx.databinding.FragmentNsgfHomeNewbornZoneBinding;
import com.zhht.htzx.databinding.ItemCouponBinding;
import com.zhht.htzx.databinding.ItemProductBinding;
import com.nsgf.library.domain.request.AccountRequester;
import com.nsgf.library.ui.page.BaseActivity;
import com.nsgf.library.ui.page.StateHolder;
import com.nsgf.library.utils.ToastUtils;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 商品列表
 */
public class ProduceListActivity extends BaseActivity {

    private ProductListStates mStates;

    private SimpleDataBindingAdapter<ProductBean, ItemProductBinding> mAdapter;

    private AccountRequester mAccountRequester;

    private int position = 0;

    @Override
    protected void initViewModel() {
        mStates = new ProductListStates();
        mAccountRequester = new AccountRequester();
    }

    @Override
    protected DataBindingConfig getDataBindingConfig() {
        mAdapter = new SimpleDataBindingAdapter<ProductBean, ItemProductBinding>(this, R.layout.item_product, DiffUtils.getInstance().getProductItemCallback()) {
            @Override
            protected void onBindItem(ItemProductBinding binding, ProductBean item, RecyclerView.ViewHolder holder) {
                binding.setVm(item);
                if (StringUtil.isEmpty(item.getTenantName())) {
                    binding.tvItemProductTenantName.setVisibility(GONE);
                } else
                    binding.tvItemProductTenantName.setVisibility(VISIBLE);
            }
        };
        return new DataBindingConfig(R.layout.activity_product_list, BR.vm, mStates)
                .addBindingParam(BR.adapter, mAdapter);
    }

    private ActivityProductListBinding mBinding;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getLifecycle().addObserver(mAccountRequester);
        mBinding = (ActivityProductListBinding) getBinding();
        mStates.titleBar.set(getIntent().getStringExtra("title"));

        mBinding.recyclerView.setItemAnimator(null);
        position = getIntent().getIntExtra("position", 0);

        mAdapter.setOnItemClickListener((viewId, item, index) ->
                startActivity(new Intent()
                        .putExtra("id", -1 == position ? item.getId() : item.getSpuId())
                        .setClass(ProduceListActivity.this, ProductDetailActivity.class)));


        if (-1 == position) {
            mStates.titleBar.set("搜索商品");
            page = 1;
            mStates.searchName.set(getIntent().getStringExtra("searchName"));
            mBinding.etProductSearch.setVisibility(VISIBLE);
            // 设置加载更多监听
            mBinding.swipeRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
                @Override
                public void onLoadMore(RefreshLayout refreshLayout) {
                    page++;
                    mAccountRequester.getProductList(page, mStates.searchName.get());
                }
            });
        }
        loadInitialData();
        setupRefreshLayout();
        mBinding.swipeRefreshLayout.autoRefresh();

        mBinding.etProductSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    page = 1;
                    // 在这里执行搜索操作
                    mBinding.swipeRefreshLayout.autoRefresh();
                    return true; // 消费事件，防止默认行为
                }
                return false; // 不消费事件，允许默认行为
            }
        });
    }


    private void setupRefreshLayout() {
        // 设置下拉刷新监听
        mBinding.swipeRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                if (-1 == position) {

                    page = 1;
                    mAccountRequester.getProductList(page, mStates.searchName.get());
                } else {

                    page = 0;
                    mAccountRequester.queryYouXuanList(page, position);
                }

            }
        });

    }


    private void loadInitialData() {
        mAccountRequester.getProductResult().observe(this, new Observer<ResponseStatus<ProductBean>>() {
            @Override
            public void onChanged(ResponseStatus<ProductBean> productBeanResponseStatus) {

                if (productBeanResponseStatus.getResponseCode() == 0) {
                    if (page == 1) {
                        mBinding.swipeRefreshLayout.finishRefresh();
                        mStates.list.set(productBeanResponseStatus.getData().getList());
                        if (!mStates.list.get().isEmpty())
                            mBinding.ivListNotData.setVisibility(GONE);
                        else mBinding.ivListNotData.setVisibility(VISIBLE);
                    } else {
                        mBinding.swipeRefreshLayout.finishLoadMore();

                        List<ProductBean> currentList = mStates.list.get();
                        if (currentList != null) {
                            currentList.addAll(productBeanResponseStatus.getData().getList());
                            mStates.list.set(currentList);
                        }
                    }
                } else {
                    ToastUtils.showShortToast(productBeanResponseStatus.getMsg());
                }
            }
        });
        mAccountRequester.getProductBeanResult().observe(this, new Observer<ResponseStatus<List<ProductBean>>>() {
            @Override
            public void onChanged(ResponseStatus<List<ProductBean>> listResponseStatus) {

                if (listResponseStatus.getResponseCode() == 0) {
                    if (page == 0) {
                        mBinding.swipeRefreshLayout.finishRefresh();
                        mStates.list.set(listResponseStatus.getData());
                        if (!mStates.list.get().isEmpty())
                            mBinding.ivListNotData.setVisibility(GONE);
                        else mBinding.ivListNotData.setVisibility(VISIBLE);
                    } else {
                        mBinding.swipeRefreshLayout.finishLoadMore();
                        Objects.requireNonNull(mStates.list.get()).addAll(listResponseStatus.getData());
                    }
                    mAdapter.notifyDataSetChanged();
                } else {
                    ToastUtils.showShortToast(listResponseStatus.getMsg());
                }
            }
        });
    }


    private int page = 0;
    private final Handler handler = new Handler(Looper.getMainLooper());


    public static class ProductListStates extends StateHolder {

        public final State<List<ProductBean>> list = new State<>(new ArrayList<>());
        public final State<String> searchName = new State<>("");
    }
}
